package hczc.longcai.com.hccrowdfunding.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;

import hczc.longcai.com.hccrowdfunding.R;
import hczc.longcai.com.hccrowdfunding.activity.beans.Code;
import hczc.longcai.com.hccrowdfunding.activity.beans.RegInfo;
import hczc.longcai.com.hccrowdfunding.application.BaseApplication;
import hczc.longcai.com.hccrowdfunding.utils.httputils.HttpPath;
import hczc.longcai.com.hccrowdfunding.utils.httputils.LoadDatas;
import hczc.longcai.com.hccrowdfunding.utils.json.ParseJSON;

public class RegisterActivity extends BaseActivity implements View.OnClickListener {


    /**
     * 发送验证码时手机号输入为空
     */
    private static final int NUMBER_EMPTY = 0;
    /**
     * 验证码发送成功
     */
    private static final int SEND_SUCCESS = 1;
    private static final String TAG = "RegisterActivity";

    private int state = 0;
    private TextView title;
    private RelativeLayout relativeLayout;
    private View head_fenge;
    /**
     * 手机号输入框
     */
    private EditText number;
    /**
     * 验证码输入框
     */
    private EditText code;
    /**
     * 密码输入框
     */
    private EditText passwd;
    /**
     * 加载数据的工具类
     */
    private LoadDatas loadDatas;

    /**
     * 返回的和验证码匹配的验证码ID
     */
    private String codeId;

    /**
     * 注册的异步任务
     */
    private RegisterAsyncTask asyncTask;

    /**
     * 获取sharedpreference实例用来存储登陆状态
     */
    private SharedPreferences mSharedPreferences;
    /**
     * 更新UI的handler
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            switch (what) {
                case NUMBER_EMPTY:
                    Toast.makeText(RegisterActivity.this, "请输入手机号码", Toast.LENGTH_SHORT).show();
                    setFocus(number);
                    break;
                //验证码发送成功在这里获取信息
                case SEND_SUCCESS:
                    Code code = (Code) msg.obj;
                    String status = code.getStatus();
                    if ("1".equals(status)) {
                        codeId = code.getId();
                        Toast.makeText(RegisterActivity.this, code.getTips(), Toast.LENGTH_SHORT).show();
                        Log.d(TAG, code.toString());
                    } else {
                        Toast.makeText(RegisterActivity.this, code.getTips(), Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_find);

        mSharedPreferences = BaseApplication.mSharedPreferences;
        loadDatas = new LoadDatas();

        initDatas();

        initViews();
    }

    private void initDatas() {
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            state = extras.getInt("state");
        }
    }

    private void initViews() {
        findViewById(R.id.head_back).setOnClickListener(this);
        title = ((TextView) findViewById(R.id.head_title));
        title.setText("注册");
        findViewById(R.id.headbar_background).setBackgroundColor(Color.parseColor("#00000000"));


//        button = ((TextView) findViewById(R.id.register_find_button));
        relativeLayout = ((RelativeLayout) findViewById(R.id.find_pic));
        head_fenge = findViewById(R.id.find_fenge);

        initInput();

    }

    /**
     * 初始化几个输入框及注册按钮
     */
    private void initInput() {
        number = ((EditText) findViewById(R.id.register_input_number_edit));
        code = ((EditText) findViewById(R.id.register_input_code_edit));
        passwd = ((EditText) findViewById(R.id.register_input_passwd_edit));
        //获取验证码按钮
        findViewById(R.id.register_hqyzm).setOnClickListener(this);
        //注册按钮
        findViewById(R.id.register_button).setOnClickListener(this);
    }


    /**
     * 判断注册是否成功
     */

    private void registerSuccess() {
        String c_number = number.getText().toString().trim();
        String c_code = code.getText().toString().trim();
        String c_passwd = passwd.getText().toString().trim();

        if (isEmpty(c_number, c_code, c_passwd)) {
            asyncTask = new RegisterAsyncTask(c_number, c_passwd, c_code, codeId);
            asyncTask.execute(((Void) null));
        }
    }

    /**
     * 判断输入的数据是否符合条件
     *
     * @param c_number 电话号码
     * @param c_code   验证码
     * @param c_passwd 密码
     * @return 若符合条件返回true
     */
    private boolean isEmpty(String c_number, String c_code, String c_passwd) {
        boolean flag = true;
        if (TextUtils.isEmpty(c_number)) {
            Toast.makeText(RegisterActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
            setFocus(number);
            flag = false;
            return flag;
        } else if (c_number.length() != 11) {
            Toast.makeText(RegisterActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            setFocus(number);
            flag = false;
            return flag;
        }

        if (TextUtils.isEmpty(c_code)) {
            Toast.makeText(RegisterActivity.this, "验证码不能为空", Toast.LENGTH_SHORT).show();
            setFocus(code);
            flag = false;
            return flag;
        }

        if (TextUtils.isEmpty(c_passwd)) {
            Toast.makeText(RegisterActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
            setFocus(passwd);
            flag = false;
            return flag;
        } else if (c_passwd.length() < 6) {
            Toast.makeText(RegisterActivity.this, "密码过短，请重新输入", Toast.LENGTH_SHORT).show();
            passwd.setText("");
            setFocus(passwd);
            flag = false;
            return flag;
        } else if (c_passwd.length() > 20) {
            Toast.makeText(RegisterActivity.this, "密码过长，请重新输入", Toast.LENGTH_SHORT).show();
            passwd.setText("");
            setFocus(passwd);
            flag = false;
            return flag;
        }


        return flag;
    }

    /**
     * 设置EditText的焦点
     *
     * @param et 要设置的EditText
     */
    private void setFocus(View et) {
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);
        et.requestFocus();
        et.findFocus();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.head_back:
                finish();
                break;

            case R.id.register_button:
                registerSuccess();
                break;

            case R.id.register_hqyzm:
                final String c_number = number.getText().toString().trim();
//                Toast.makeText(RegisterActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                if (TextUtils.isEmpty(c_number)) {
                    handler.sendEmptyMessage(NUMBER_EMPTY);
                } else {
                    //发送验证码的子线程，返回验证码类
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                byte[] regs = loadDatas.getDatas(HttpPath.getURL_Code(c_number, "reg"));
                                String s = new String(regs, 0, regs.length);
                                Code code = ParseJSON.parseCode(s);
                                Message message = Message.obtain();
                                message.obj = code;
                                message.what = SEND_SUCCESS;
                                handler.sendMessage(message);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    break;
                }
        }
    }

    /**
     * 发送注册请求的异步任务
     */
    class RegisterAsyncTask extends AsyncTask<Void, Void, RegInfo> {

        private String txtUsername;
        private String txtPwd;
        private String txtCode;
        private String codeId;

        public RegisterAsyncTask(String txtUsername, String txtPwd, String txtCode, String codeId) {
            this.txtUsername = txtUsername;
            this.txtPwd = txtPwd;
            this.txtCode = txtCode;
            this.codeId = codeId;
        }

        @Override
        protected RegInfo doInBackground(Void... params) {
            RegInfo info = null;
            try {
                String c_reg = HttpPath.getURL_Register(txtUsername, txtPwd, txtCode, codeId);
                byte[] datas = loadDatas.getDatas(c_reg);
                String JSON = new String(datas, 0, datas.length);
                info = ParseJSON.parseReg(JSON);
                String status = info.getStatus();
                if ("1".equals(status)){
                    int uid = info.getUid();
                    String url_userinfo = HttpPath.getURL_Userinfo(String.valueOf(uid));
                    byte[] user_datas = loadDatas.getDatas(url_userinfo);
                    String userJSON = new String(user_datas, 0, user_datas.length);
                    ParseJSON.parseUser(userJSON);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return info;
        }

        @Override
        protected void onPostExecute(RegInfo regInfo) {
            super.onPostExecute(regInfo);
            String tips;
            String status = regInfo.getStatus();
            if ("0".equals(status)) {
                tips = regInfo.getTips();
                Toast.makeText(RegisterActivity.this, tips, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(RegisterActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
                int uid = regInfo.getUid();
                setUid(uid);
                finish();
            }
        }
    }

    private void setUid(int uid) {
        String s = String.valueOf(uid);
        SharedPreferences.Editor edit = mSharedPreferences.edit();
        edit.putBoolean("isLogin",true);
        edit.putString("uid",s);
        edit.commit();
    }
}
